﻿using System;
using DAL.POCO;
using DAL.Repositories;

namespace GameAdmin.Pages
{
    public partial class answer : System.Web.UI.Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            btnSave.Click += new EventHandler(btnSave_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (RouteData.Values["id"] != null)
                {
                    LoadOriginalValues();
                }
                else if (RouteData.Values["questionId"] != null)
                {
                    InitAdder();
                }
                else return;

                lnkBack.NavigateUrl += txtQuestionId.Text;
            } 
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    Answer a = new Answer();
                    a.questionId = Int32.Parse(txtQuestionId.Text);
                    a.mark = ddlMarks.SelectedValue;
                    a.text = txtText.Text;
                    a.correct = chkBoxCorrect.Checked;

                    if (txtId.Text != "")
                    {
                        // update the existing one
                        a.id = Int32.Parse(txtId.Text);
                        AnswerRepository.Update(a);
                    }
                    else
                    {
                        AnswerRepository.Insert(a);
                    }

                    Response.Redirect("~/answers/question-" + txtQuestionId.Text, true);
                }
                catch (Exception ex)
                {
                    lblMessage.Visible = true;
                    lblMessage.Text = ex.Message;
                }
            }
        }

        private void InitAdder()
        {
            txtQuestionId.Text = (string)RouteData.Values["questionId"];
        }

        private void LoadOriginalValues()
        {
            string idString = (string)RouteData.Values["id"];
            int id = Int32.Parse(idString);

            Answer a = AnswerRepository.GetAnswer(id);

            txtId.Text = idString;
            txtQuestionId.Text = a.questionId.ToString();
            ddlMarks.SelectedValue = a.mark;
            txtText.Text = a.text;
            chkBoxCorrect.Checked = a.correct;
        }
    }
}